package com.showsu.editor.utils.baidu;


import com.baidu.aip.ocr.AipOcr;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Base64;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

@Slf4j
@Component
public class AipOcrHandle extends BaseBaiDuAip<AipOcr> {

    @Value("${baidu.ocr.appId}")
    private String appId;
    @Value("${baidu.ocr.apiKey}")
    private String apiKey;
    @Value("${baidu.ocr.secretKey}")
    private String secretKey;

    @Override
    public void initClient(String appId, String apiKey, String secretKey) {
        this.client =new AipOcr(appId,apiKey,secretKey);
        // 可选：设置网络连接参数
//        this.client.setConnectionTimeoutInMillis(2000);
//        this.client.setSocketTimeoutInMillis(60000);
    }

    @PostConstruct
    public void init(){
        System.out.println("开始实例化 百度AipOcr");
        this.initClient(appId,apiKey,secretKey);
        System.out.println("结束实例化 百度AipOcr");
    }


    /**
     * 通用文字识别（高精度版）
     * @param file 参数为图片二进制数组
     * @return
     */
    public JSONObject basicAccurateGeneral(byte[] file) {
        if(file==null){
            return null;
        }
        // 传入可选参数调用接口
        HashMap<String, String> options = new HashMap<String, String>();
        options.put("detect_direction", "false");
        options.put("probability", "false");
        options.put("paragraph", "false");
        return this.client.basicAccurateGeneral(file, options);
    }

    /**
     * 通用文字识别（高精度版）
     * @param url 参数为url图片路径
     * @return
     */
    public List<String> basicAccurateGeneral(String url) {
        List<String> result=null;
        byte[] q=null;
        try {
            q = loadAsByte(url);
        }catch (Exception e){
            log.error("通用文字识别（高精度版）功能-获取图片时报错-errorMsg:{}-url：{}-result：{}",e.getMessage(), url);
        }
        if(q==null){
            return result;
        }
        JSONObject baiduResult = this.basicAccurateGeneral(q);
        if(baiduResult!=null){
            result=new LinkedList<String>();
            if(baiduResult.getInt("words_result_num")>0) {
                JSONArray wordsResult = baiduResult.getJSONArray("words_result");
                for (int i = 0; i < wordsResult.length(); i++) {
                    JSONObject words = wordsResult.getJSONObject(i);
                    result.add(words.getString("words"));
                }
            }
        }else {
            log.error("通用文字识别（高精度版）功能-百度接口报错-url：{}", url);
        }
        return result;
    }

    public String loadAsBase64(String url) throws IOException, InterruptedException {
        byte[] data = this.loadAsByte(url);
        return Base64.getEncoder().encodeToString(data);
    }
    public byte[] loadAsByte(String url) throws IOException, InterruptedException {
        URL urlfile=new URL(url);
        URLConnection uc=urlfile.openConnection();
        byte[] data = null;
        int i=3;
        while (i-->0){
            try (InputStream fis = uc.getInputStream()) {
                i=0;
                int fileSize = uc.getContentLength();
                int offset = 0;
                data = new byte[fileSize];
                while (offset<fileSize){
                    int result = fis.read(data, offset, data.length - offset);
                    if (result == -1) {
                        break;
                    }
                    offset += result;
                }
            } catch (IOException e) {
                Thread.sleep(3000);
                log.error(e.getMessage());
            }
        }
        return data;
    }



    public static void main(String[] args) throws Exception {
        AipOcrHandle aipOcrHandle=new AipOcrHandle();
        aipOcrHandle.appId="41231191";
        aipOcrHandle.apiKey="0rVOd0mAmbFItkmiwsmlRGy1";
        aipOcrHandle.secretKey="YXWTk8cuToktW4eWbY2hswTTlDBYUlnr";
        aipOcrHandle.init();
        List<String> result=aipOcrHandle.basicAccurateGeneral("https://showsu.oss-cn-hangzhou.aliyuncs.com/water/20231018/c3c89c8ba5094b58a6b28577249bdb81.png");
        System.out.println(result.toString());
    }


}
